package edu.ynu.se.xiecheng.achitectureclass.realm;

import edu.ynu.se.xiecheng.achitectureclass.entity.User;
import edu.ynu.se.xiecheng.achitectureclass.service.UserService;
import edu.ynu.se.xiecheng.achitectureclass.util.JWTUtils;
import edu.ynu.se.xiecheng.achitectureclass.util.JwtToken;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import javax.annotation.Resource;

public class CustomRealm extends AuthorizingRealm {
    /**
     * 只要配置了在Spring里管理（@Bean），就可以使用Autowired注入
     */
    @Resource
    UserService userService;

    /**
     * 重写supports方法：支持自定义JWTToken的认证与授权
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }


    /**
     * 授权方法
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了 => 授权方法doGetAuthorizationInfo");
        //获取用户名（能执行到这一步，说明已经通过了认证，无需验证token）
        String username = JWTUtils.getUserName(principalCollection.toString());
        //System.out.println("====getPrimaryPrincipal====" + (String)principalCollection.getPrimaryPrincipal());
        //System.out.println("====toString====" + principalCollection.toString());二者都能获取token
        //数据库查询角色权限信息
        User user = userService.getUserByUsername(username);
        //如果权限不为空
        if(user.getHasRole()!=null){
            //返回角色权限信息
            SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
            authorizationInfo.addRole(user.getHasRole());
            return authorizationInfo;
        }
        return null;
    }

    /**
     * 认证方法（只做认证判断，并不进行真正的登录，真登录在controller里）
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("执行了 => 认证方法doGetAuthenticationInfo");
        //从主体传过来的认证信息中，获取需要认证的token
        String token = (String)authenticationToken.getPrincipal();
        //数据库查询
        String userName = JWTUtils.getUserName(token);
        //判断签发的token是否真实有效
        if(userName==null || !JWTUtils.verifyToken(token)){
            System.out.println("token无效！");
            throw new AuthenticationException("token无效！");
        }
        //判断用户是否真实有效
        User user = userService.getUserByUsername(userName);
        if(user == null){
            System.out.println("用户不存在！");
            throw new AuthenticationException("用户不存在！");
        }
        //返回token即可
        //因为：-默认的密码比对器是比较 Principal 和 Credentials 是否equal
        //      -JWTToken的凭证和密钥都是token，而这里认证又都通过了，所以需要使后续的比对通过不报错
        return new SimpleAuthenticationInfo(token,token,this.getName());
    }
}
